package com.woniuxy.service.hospital.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.Dept;
import com.woniuxy.entity.Home;
import com.woniuxy.entity.Hospital;
import com.woniuxy.entity.HospitalExample;
import com.woniuxy.mapper.DeptMapper;
import com.woniuxy.mapper.HomeMapper;
import com.woniuxy.mapper.HospitalMapper;
import com.woniuxy.mapper.custom.CustomDeptMapper;
import com.woniuxy.mapper.custom.CustomHomeMapper;
import com.woniuxy.service.hospital.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class HomeServiceImpl implements HomeService {
    @Autowired
    private CustomHomeMapper homeMapper;
    @Autowired
    private HospitalMapper hospitalMapper;
    @Autowired
    private CustomDeptMapper deptMapper;

    @Override
    public PageInfo<Home> findAll(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Home> homes = homeMapper.selectByExample(null);
        setHomeInfo(homes);
        PageInfo info = new PageInfo(homes);
        return info;
    }

    @Override
    public int save(Home home) {
        int rows = homeMapper.insertSelective(home);
        return rows;
    }

    @Override
    public int update(Home home) {
        int rows = homeMapper.updateByPrimaryKeySelective(home);
        return rows;
    }

    @Override
    public int delete(Integer hId) {
        int rows = homeMapper.deleteByPrimaryKey(hId);
        return rows;
    }

    @Override
    public PageInfo<Home> findSelect(Dept dept,Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Home> homes = new ArrayList<>();
        if(dept.getDeptId()==null){
            Hospital hospital = hospitalMapper.selectByPrimaryKey(dept.gethId());
            List<Dept> list = deptMapper.selByHid(hospital.gethId());
            for (Dept dept1 : list) {
                List<Home> homes1 = homeMapper.selByDeptId(dept1.getDeptId());
                setHomeInfo(homes1);
                homes.addAll(homes1);
            }
        }else{
            homes = homeMapper.selByDeptId(dept.getDeptId());
            setHomeInfo(homes);
        }
        PageInfo info = new PageInfo(homes);
        return info;
    }

    private void setHomeInfo(List<Home> homes) {
        for (Home home : homes) {
            home.setDeptName(homeMapper.findDeptNameByDeptId(home.getDeptId()));
            home.sethName(homeMapper.findHospitalByHid(home.gethId()));
        }
    }



}
